<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.currentId ? '新增' : '修改'"
    :close-on-click-modal="false"
    style="width: 80%;"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @onclick="onSubmit()"
    >
      <el-form-item
        label="征集活动标题"
        prop="title"
      >
        <el-input
          v-model="dataForm.title"
          controls-position="right"
          :min="0"
          label="征集动标题"
        />
      </el-form-item>
      <el-form-item
        label="征集活动封面"
        prop="coverImage"
      >
        <pic-upload
          v-model="dataForm.coverImage"
          @update:model-value="checkImage"
        />
      </el-form-item>
      <el-form-item
        label="参赛对象"
        prop="entrants"
      >
        <el-input
          v-model="dataForm.entrants"
          controls-position="right"
          :min="0"
          label="参赛对象"
        />
      </el-form-item>
      <el-form-item
        label="主办单位"
        prop="organizer"
      >
        <el-input
          v-model="dataForm.organizer"
          controls-position="right"
          :min="0"
          label="主办单位"
        />
      </el-form-item>
      <el-form-item
        label="奖项设置"
        prop="award"
      >
        <el-input
          v-model="dataForm.award"
          controls-position="right"
          :min="0"
          label="奖项设置"
        />
      </el-form-item>
      <el-form-item
        label="活动标签"
        prop="activityTag"
      >
        <el-tag
          v-for="tag in tagParam.dynamicTags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{
            tag
          }}
        </el-tag>
        <el-input
          v-if="tagParam.inputVisible"
          ref="saveTagInput"
          v-model="tagParam.inputValue"
          size="small"
          class="input-new-tag"
          @keydown.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button
          v-else
          size="small"
          class="button-new-tag"
          @click="showInput"
        >
          + New Tag
        </el-button>
      </el-form-item>
      <el-row>
        <el-form-item
          label="征集开始时间"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="征集结束时间"
          prop="endTime"
        >
          <el-date-picker
            v-model="dataForm.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-row>
      <el-form-item
        label="申报截止时间"
        prop="startTime"
      >
        <el-date-picker
          v-model="dataForm.stopTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-row>
        <el-form-item
          label="评审开始时间"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.reviewStartTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="评审结束时间"
          prop="endTime"
        >
          <el-date-picker
            v-model="dataForm.reviewEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-row>
      <el-form-item
        label="征集活动附件"
        prop="coverFileList"
      >
        <mul-file-upload
          v-model="dataForm.coverFileList"
          @update:model-value="checkFile"
        />
      </el-form-item>
      <div
        style="margin-top: 20px"
      >
        <el-table
          :data="dataForm.textList"
          border
          style="width: 100%;"
          class="table-con"
        >
          <el-table-column
            header-align="center"
            align="center"
            label="内容标题"
            min-width="20%"
          >
            <template #default="scope">
              <el-form-item
                :prop="`textList.${scope.$index}.title`"
                label-width="0px"
              >
                <el-input
                  v-model="scope.row.title"
                  controls-position="right"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="内容描述"
            min-width="80%"
          >
            <template #default="scope">
              <el-form-item
                :prop="`textList.${scope.$index}.description`"
                label-width="0px"
              >
                <tiny-mce
                  ref="contentRef"
                  v-model="scope.row.description"
                  style="width:100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="列表展示"
            min-width="5%"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.isShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="addTextList()"
        >
          点击征集活动内容模块
        </el-button>
        <el-button
          v-if="dataForm.textList.length > 0"
          type="danger"
          @click="delTextList()"
        >
          删除最后一行
        </el-button>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="warning"
          @click="onTemplateFrom()"
        >
          作品征集申报模板
        </el-button>
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          确定
        </el-button>
      </div>
    </template>
    <!--参与用户信息-->
    <templateFrom
      v-if="onTemplateFromVisible"
      ref="onTemplateFromRef"
      @refresh-data-list="setTemplateId($event)"
    />
  </el-dialog>
</template>

<script setup>
import {ElMessage} from 'element-plus'
import {Debounce} from '@/utils/debounce'
import templateFrom from './templateFrom.vue'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataForm = reactive({
  id: 0,
  currentId: 0,
  templateId: 0,
  title: '',
  status: 0,
  coverImage: null,
  coverFileList: null,
  coverFile: null,
  coverFileName: null,
  textList: [],
  fileList: []
})
const dataRule = reactive({
  title: [
    {required: true, message: '活动标题不能为空', trigger: 'blur'}
  ],
  coverImage: [
    {required: true, message: '活动封面图片不能为空', trigger: 'blur'}
  ],
  templateId: [
    {required: true, message: '作品征集申报不能为空', trigger: 'blur'}
  ]
})
const isSubmit = ref(false)
const dataFormRef = ref(null)
const tagParam = reactive({
  dynamicTags: [],
  inputVisible: false,
  inputValue: ''
})
const init = (id) => {
  visible.value = true
  dataForm.currentId = id || 0
  dataForm.id = id || 0
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.id) {
    console.log(1)
    // 修改
    http({
      url: http.adornUrl(`/admin/submissionsArt/info/${dataForm.id}`),
      method: 'get',
      params: http.adornParams()
    })
      .then(({data}) => {
        visible.value = true
        dataForm.id = data.id
        dataForm.title = data.title
        dataForm.coverImage = data.coverImage
        dataForm.entrants = data.entrants
        dataForm.organizer = data.organizer
        dataForm.award = data.award
        tagParam.dynamicTags = JSON.parse(data.artTag)
        dataForm.startTime = data.startTime
        dataForm.endTime = data.endTime
        dataForm.stopTime = data.stopTime
        dataForm.reviewStartTime = data.reviewStartTime
        dataForm.reviewEndTime = data.reviewEndTime
        dataForm.coverFileList = data.coverFileList
        dataForm.templateId = data.templateId
        dataForm.textList = data.textList
      })
  } else {
    // 初始化
    tagParam.dynamicTags = []
    dataForm.stopTime = null
    dataForm.reviewStartTime = null
    dataForm.reviewEndTime = null
    dataForm.coverFileList = []
    dataForm.templateId = 0
    dataForm.textList = []
  }
}
defineExpose({init})

// 表单提交
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (dataForm.templateId === 0) {
        ElMessage({
          message: '作品征集申报模板还未配置',
          type: 'error',
          duration: 1000,
          onClose: () => {
          }
        })
        return;
      }
      if (isSubmit.value) {
        return;
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/admin/submissionsArt/' + (dataForm.id ? 'update' : 'add')),
        method: 'post',
        data: http.adornData({
          id: dataForm.id || undefined,
          title: dataForm.title,
          coverImage: dataForm.coverImage,
          entrants: dataForm.entrants,
          organizer: dataForm.organizer,
          award: dataForm.award,
          artTag: JSON.stringify(tagParam.dynamicTags),
          startTime: dataForm.startTime,
          endTime: dataForm.endTime,
          stopTime: dataForm.stopTime,
          reviewStartTime: dataForm.reviewStartTime,
          reviewEndTime: dataForm.reviewEndTime,
          coverFileList: dataForm.coverFileList,
          templateId: dataForm.templateId,
          textList: dataForm.textList
        })
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              isSubmit.value = false
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
    }
  })
})

/**
 * 重新校验表单pic字段
 */
const checkImage = () => {
  dataFormRef.value?.validateField('coverImage')
}
const checkFile = () => {
  dataFormRef.value?.validateField('coverFileList')
}

/**
 * 活动标签
 */
const handleClose = (tag) => {
  tagParam.dynamicTags.splice(tagParam.dynamicTags.indexOf(tag), 1)
}
const showInput = () => {
  tagParam.inputVisible = true
  this.$nextTick(() => {
    this.$refs.saveTagInput.$refs.input.focus()
  })
}
const handleInputConfirm = () => {
  const inputValue = tagParam.inputValue
  if (inputValue) {
    tagParam.dynamicTags.push(inputValue)
  }
  tagParam.inputVisible = false
  tagParam.inputValue = ''
}

const addTextList = () => {
  dataForm.textList.push({})
}
const delTextList = () => {
  dataForm.textList.pop()
}
const onTemplateFromVisible = ref(false)
const onTemplateFromRef = ref(null)
const onTemplateFrom = () => {
  onTemplateFromVisible.value = true
  nextTick(() => {
    onTemplateFromRef.value?.init(dataForm.templateId)
  })
}
const setTemplateId = (id) => {
  dataForm.templateId = id;
}
</script>

<style scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
